<?php
class UserAction extends Action
{
    public function index()
    {
        if (!$this->check())
            redirect(__ROOT__ . '/Index/login', 0, ' <script>alert("请先登陆！")</script>');
        if (isset($_POST['username']) && isset($_POST['password'])) {
            if ($_POST['username'] == session('username')) {
                $user         = M('User');
                $data['pass'] = md5(md5($_POST['password']));
                if ($user->where("user='%s'", $_POST['username'])->save($data)) {
                    redirect(__ROOT__ . '/Index', 1, '<script>alert("密码修改成功~")</script>');
                } else {
                    redirect(__ROOT__ . '/User', 1, '<script>alert("密码修改失败~")</script>');
                }
            } else {
                redirect(__ROOT__ . '/User', 1, '<script>alert("非法操作~")</script>');
            }
        }
        $this->display();
    }
    
    //判断登陆是否过时
    private function check()
    {
        $cookie = cookie('token');
        $login  = M('user_login');
        $data   = $login->where('token="%s"', $cookie)->find();
        
        if ($cookie != null && $cookie != "" && $data != null && $data != false) {
            $id   = $data['id'];
            $date = $data['dietime'];
            
            if (strtotime($date) > time()) {
                $User = M("user");
                $user = $User->where("id = '%d'", $id)->find();
                session('username', $user['user']);
                session('power', $user['power']);
                return true;
            }
        }
        return false;
    }
}